package com.web.cloud.viewmodel.pub;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.web.cloud.exception.BusinessException;
import com.web.cloud.i18n.MessageUtils;

import java.io.Serializable;

/**
 * Created by liuhaiming on 2016-05-29.
 */
public class JsonResponse<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    public static final String SUCCESS = "000000";
    public static final String ERROR = "100000";
    @JsonProperty("flag")
    private String retcode;
    @JsonProperty("desc")
    private String retmsg;
    @JsonProperty("data")
    private T data;

    protected JsonResponse(String code, String message, T data) {
        this.retcode = code;
        this.retmsg = message;
        this.data = data;
    }

    public String getRetcode() {
        return this.retcode;
    }

    public void setRetcode(String retcode) {
        this.retcode = retcode;
    }

    public String getRetmsg() {
        return this.retmsg;
    }

    public void setRetmsg(String retmsg) {
        this.retmsg = retmsg;
    }

    public T getData() {
        return this.data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> JsonResponse<T> success(T data) {
        return new JsonResponse("000000", "success", data);
    }

    public static <T> JsonResponse<T> error(Throwable e) {
        if(e instanceof BusinessException) {
            String code = ((BusinessException)e).getCode();
            return error(code, e.getMessage());
        } else {
            return error("100000", e.toString());
        }
    }

    public static <T> JsonResponse<T> error(String code) {
        return error((Throwable)(new BusinessException(code)));
    }

    public static <T> JsonResponse<T> error(String code, Object[] args) {
        return error((Throwable)(new BusinessException(code, args)));
    }

    public static <T> JsonResponse<T> error(String code, String message) {
        return error(code, message, (T)null);
    }

    public static <T> JsonResponse<T> error(String code, String message, T data) {
        return new JsonResponse(code, message, data);
    }

    public static <T> JsonResponse<T> info(String code, Object[] args, T data) {
        String message = MessageUtils.getMessage(code, args);
        return new JsonResponse(code, message, data);
    }
}

